<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item prop="account" :label="$t('user.account')">
        <el-input v-model="dataForm.account" :placeholder="$t('user.account')"/>
      </el-form-item>
      <el-form-item prop="companyName" :label="$t('companyName')">
        <el-select
                v-model="dataForm.companyId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="请输入企业名称关键词"
                :remote-method="remoteMethod"
                :loading="loading"
                style="width: 100%"  >
          <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="deptName" :label="$t('user.deptName')" class="dept-list">
        <el-popover v-model="deptListVisible" ref="deptListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="deptList"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            ref="deptListTree"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="deptListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.deptName" v-popover:deptListPopover :readonly="true" :placeholder="$t('user.deptName')"/>
      </el-form-item>
      <el-form-item prop="password" :label="$t('user.password')" :class="{ 'is-required': !dataForm.id }" v-if="!dataForm.id">
        <el-input v-model="dataForm.password" type="password" :placeholder="$t('user.password')"/>
      </el-form-item>
      <el-form-item prop="comfirmPassword" :label="$t('user.comfirmPassword')" :class="{ 'is-required': !dataForm.id }" v-if="!dataForm.id">
        <el-input v-model="dataForm.comfirmPassword" type="password" :placeholder="$t('user.comfirmPassword')"/>
      </el-form-item>
      <el-form-item prop="name" :label="$t('user.realName')">
        <el-input v-model="dataForm.name" :placeholder="$t('user.realName')"/>
      </el-form-item>
      <el-form-item prop="mobile" :label="$t('user.mobile')">
        <el-input v-model="dataForm.mobile" :placeholder="$t('user.mobile')"/>
      </el-form-item>
      <el-form-item prop="gender" :label="$t('user.gender')" size="mini">
        <el-radio-group v-model="dataForm.gender">
          <el-radio :label="0">{{ $t('user.gender0') }}</el-radio>
          <el-radio :label="1">{{ $t('user.gender1') }}</el-radio>
          <el-radio :label="2">{{ $t('user.gender2') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="email" :label="$t('user.email')">
        <el-input v-model="dataForm.email" :placeholder="$t('user.email')"/>
      </el-form-item>

      <el-form-item prop="roleIdList" :label="$t('user.roleIdList')" class="role-list">
        <el-select v-model="dataForm.roleIdList" multiple :placeholder="$t('user.roleIdList')">
          <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="status" :label="$t('user.status')" size="mini">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">{{ $t('user.status0') }}</el-radio>
          <el-radio :label="1">{{ $t('user.status1') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'
import { isEmail, isMobile } from '@/utils/validateHelper'
export default {
  data () {
    return {
      visible: false,
      deptList: [],
      companyList: [],
      deptListVisible: false,
      roleList: [],
      roleIdListDefault: [],
      dataForm: {
        id: '',
        name: '',
        deptId: '0',
        companyId:'',
        deptName: '',
        password: '',
        comfirmPassword: '',
        account: '',
        gender: 0,
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1
      }
    }
  },
  computed: {
    dataRule () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t('user.validate.comfirmPassword')))
        }
        callback()
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          return callback(new Error(this.$t('validate.format', { 'attr': this.$t('user.email') })))
        }
        callback()
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          return callback(new Error(this.$t('validate.format', { 'attr': this.$t('user.mobile') })))
        }
        callback()
      }
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        deptName: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        comfirmPassword: [
          { validator: validateComfirmPassword, trigger: 'blur' }
        ],
        account: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        // email: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        //   { validator: validateEmail, trigger: 'blur' }
        // ],
        mobile: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.roleIdListDefault = []
        Promise.all([
          this.getDeptList(),
          this.getRoleList()
        ]).then(() => {
          if (this.dataForm.id) {

            this.getInfo()
          }
        })
      })
    },
    // 获取企业
    getCompanyById (id) {
      return this.$axios.get('/manager/company/info/'+id).then(res => {
        if(res){
          this.companyList = [res];
        }
      }).catch(() => {})
    },
    getDeptById (id) {
      return this.$axios.get('/system/dept/info/'+id).then(res => {
        if(res){
          this.dataForm.deptName = res.name;
          this.dataForm.deptId = res.id;
        }
      }).catch(() => {})
    },
    // 获取部门列表
    getDeptList () {
      return this.$axios.get('/system/dept/getDeptTree').then(res => {
        this.deptList = res.records
      }).catch(() => {})
    },
    // 获取角色列表
    getRoleList () {
      return this.$axios.get('system/role/page').then(res => {
        this.roleList = res.records
      }).catch(() => {})
    },
    // 获取信息
    getInfo () {
      this.$axios.get(`/system/admin/info/${this.dataForm.id}`).then(res => {
        this.dataForm = {
          ...this.dataForm,
          ...res,
          roleIdList: []
        }
        this.getCompanyById(res.companyId);
        this.getDeptById(res.deptId);
        this.$refs.deptListTree.setCurrentKey(this.dataForm.deptId)
        // 角色配置, 区分是否为默认角色
        for (var i = 0; i < res.roleIdList.length; i++) {
          if (this.roleList.filter(item => item.id === res.roleIdList[i])[0]) {
            this.dataForm.roleIdList.push(res.roleIdList[i])
            continue
          }
          this.roleIdListDefault.push(res.roleIdList[i])
        }
      }).catch(() => {})
    },
    // 所属部门树, 选中
    deptListTreeCurrentChangeHandle (data, node) {
      this.dataForm.deptId = data.id
      this.dataForm.deptName = data.name
      this.deptListVisible = false
    },

    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.getCompanyList(query);
      } else {
        this.companyList = [];
      }
    },

    // 获企业客户所列表
    getCompanyList(queryName) {
      return this.$axios.get('/manager/company/page', {
        params: {
          order: 'ASC',
          orderField: 'createTime',
          current: 1,
          size: 20,
          listMode: true,
          queryItems: 'name,LIKE,' + queryName
        }
      }).then(res => {
        this.loading = false;
        this.companyList = res.records
      }).catch(() => {
      })
    },

    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http.json('/system/admin/addOrUpdate',this.dataForm).then(res => {
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false })
  }
}
</script>

<style lang="scss">
.mod-sys__user {
  .dept-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  .role-list {
    .el-select {
      width: 100%;
    }
  }
}
</style>
